package configs

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/xormplus/core"
	"github.com/xormplus/xorm"
	"log"
	"sync"
)

var (
	lock         sync.Mutex
	masterEngine *xorm.Engine
)

//主库，单例
func InstanceMaster() *xorm.Engine {
	// 判断是否已经存在
	if masterEngine != nil {
		return masterEngine
	}
	lock.Lock()
	defer lock.Unlock()
	// 判断是否已经存在 因为加锁 想要重新判断是否存在
	if masterEngine != nil {
		return masterEngine
	}

	driverSource := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8",
		Db.User, Db.Pwd, Db.Host, Db.Port, Db.DbName)
	engine, err := xorm.NewEngine(Db.Driver, driverSource)
	if err != nil {
		log.Fatalf("DbInstanceMaster%v", err)
		return nil
	}

	// Debug模式，打印全部的SQL语句，帮助对比，看ORM与SQL执行的对照关系
	engine.ShowSQL(false)
	//engine.SetTZDatabase(conf.SysTimeLocation)

	tbMapper := core.NewPrefixMapper(core.SnakeMapper{}, "t_")
	engine.SetTableMapper(tbMapper)

	masterEngine = engine
	return engine
}
